<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">忘记密码</text>
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content">
      <!-- 步骤指示器 -->
      <view class="steps">
        <view class="step-item" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
          <view class="step-circle">
            <text class="step-number">{{ currentStep > 1 ? '✓' : '1' }}</text>
          </view>
          <text class="step-text">验证邮箱</text>
        </view>
        <view class="step-line" :class="{ active: currentStep >= 2 }"></view>
        <view class="step-item" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
          <view class="step-circle">
            <text class="step-number">{{ currentStep > 2 ? '✓' : '2' }}</text>
          </view>
          <text class="step-text">重置密码</text>
        </view>
        <view class="step-line" :class="{ active: currentStep >= 3 }"></view>
        <view class="step-item" :class="{ active: currentStep >= 3 }">
          <view class="step-circle">
            <text class="step-number">3</text>
          </view>
          <text class="step-text">完成</text>
        </view>
      </view>
      
      <!-- 步骤1: 验证邮箱 -->
      <view v-if="currentStep === 1" class="step-content">
        <view class="form-card">
          <text class="form-title">验证您的邮箱</text>
          <text class="form-desc">请输入您注册时使用的邮箱地址</text>
          
          <view class="form-group">
            <text class="form-label">邮箱地址</text>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                type="text" 
                placeholder="请输入邮箱"
                v-model="formData.email"
                @input="validateEmail"
              />
              <text class="input-icon">📧</text>
            </view>
            <text class="error-text" v-if="errors.email">{{ errors.email }}</text>
          </view>
          
          <view class="form-group">
            <text class="form-label">验证码</text>
            <view class="input-wrapper code-wrapper">
              <input 
                class="form-input" 
                type="text" 
                placeholder="请输入验证码"
                v-model="formData.code"
                maxlength="6"
                @input="validateCode"
              />
              <button 
                class="code-btn" 
                :disabled="codeSending || countdown > 0 || !formData.email"
                @click="sendCode"
              >
                {{ codeButtonText }}
              </button>
            </view>
            <text class="error-text" v-if="errors.code">{{ errors.code }}</text>
          </view>
          
          <button 
            class="submit-btn" 
            :disabled="!canProceedStep1"
            @click="verifyEmailAndCode"
          >
            下一步
          </button>
        </view>
      </view>
      
      <!-- 步骤2: 重置密码 -->
      <view v-if="currentStep === 2" class="step-content">
        <view class="form-card">
          <text class="form-title">设置新密码</text>
          <text class="form-desc">请设置一个安全的新密码</text>
          
          <view class="form-group">
            <text class="form-label">新密码</text>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入新密码（6-20位）"
                v-model="formData.newPassword"
                @input="validateNewPassword"
              />
              <text class="input-icon" @click="togglePassword">
                {{ showPassword ? '👁️' : '🔒' }}
              </text>
            </view>
            <text class="error-text" v-if="errors.newPassword">{{ errors.newPassword }}</text>
          </view>
          
          <view class="form-group">
            <text class="form-label">确认密码</text>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入新密码"
                v-model="formData.confirmPassword"
                @input="validateConfirmPassword"
              />
              <text class="input-icon" @click="toggleConfirmPassword">
                {{ showConfirmPassword ? '👁️' : '🔒' }}
              </text>
            </view>
            <text class="error-text" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</text>
          </view>
          
          <button 
            class="submit-btn" 
            :disabled="!canProceedStep2"
            @click="resetPassword"
          >
            重置密码
          </button>
        </view>
      </view>
      
      <!-- 步骤3: 完成 -->
      <view v-if="currentStep === 3" class="step-content">
        <view class="success-card">
          <text class="success-icon">✓</text>
          <text class="success-title">密码重置成功</text>
          <text class="success-desc">您的密码已成功重置，请使用新密码登录</text>
          
          <button class="login-btn" @click="goToLogin">
            去登录
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import authService from '../../services/auth.js'
import { smartBack } from '../../utils/navigation.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      currentStep: 1, // 当前步骤：1-验证邮箱，2-重置密码，3-完成
      
      formData: {
        email: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      errors: {
        email: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      // 验证码相关
      codeSending: false,
      countdown: 0,
      countdownTimer: null,
      
      // 密码显示控制
      showPassword: false,
      showConfirmPassword: false,
      
      // 临时存储验证通过的数据
      verifiedEmail: '',
      verifiedCode: ''
    }
  },
  
  computed: {
    codeButtonText() {
      if (this.codeSending) return '发送中...'
      if (this.countdown > 0) return `${this.countdown}秒后重试`
      return '获取验证码'
    },
    
    canProceedStep1() {
      return this.formData.email && 
             this.formData.code && 
             this.formData.code.length === 6 &&
             !this.errors.email &&
             !this.errors.code
    },
    
    canProceedStep2() {
      return this.formData.newPassword && 
             this.formData.confirmPassword &&
             !this.errors.newPassword &&
             !this.errors.confirmPassword
    }
  },
  
  onLoad() {
    this.getStatusBarHeight()
  },
  
  onUnload() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
  
  methods: {
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
    },
    
    goBack() {
      smartBack('/pages/login/login') // 忘记密码页面返回登录页
    },
    
    // 表单验证
    validateEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!this.formData.email) {
        this.errors.email = '请输入邮箱地址'
      } else if (!emailRegex.test(this.formData.email)) {
        this.errors.email = '请输入正确的邮箱格式'
      } else {
        this.errors.email = ''
      }
    },
    
    validateCode() {
      if (!this.formData.code) {
        this.errors.code = '请输入验证码'
      } else if (this.formData.code.length !== 6) {
        this.errors.code = '验证码为6位数字'
      } else {
        this.errors.code = ''
      }
    },
    
    validateNewPassword() {
      if (!this.formData.newPassword) {
        this.errors.newPassword = '请输入新密码'
      } else if (this.formData.newPassword.length < 6) {
        this.errors.newPassword = '密码至少6位'
      } else if (this.formData.newPassword.length > 20) {
        this.errors.newPassword = '密码最多20位'
      } else {
        this.errors.newPassword = ''
      }
      
      // 如果确认密码已输入，重新验证
      if (this.formData.confirmPassword) {
        this.validateConfirmPassword()
      }
    },
    
    validateConfirmPassword() {
      if (!this.formData.confirmPassword) {
        this.errors.confirmPassword = '请再次输入密码'
      } else if (this.formData.confirmPassword !== this.formData.newPassword) {
        this.errors.confirmPassword = '两次密码不一致'
      } else {
        this.errors.confirmPassword = ''
      }
    },
    
    // 发送验证码
    async sendCode() {
      this.validateEmail()
      if (this.errors.email) return
      
      this.codeSending = true
      
      try {
        console.log('📧 发送验证码到:', this.formData.email)
        
        // 调用后端接口发送验证码
        await authService.sendEmailCode({
          email: this.formData.email,
          type: 'reset_password'
        })
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        // 开始倒计时
        this.countdown = 60
        this.countdownTimer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(this.countdownTimer)
          }
        }, 1000)
        
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      } finally {
        this.codeSending = false
      }
    },
    
    // 验证邮箱和验证码
    async verifyEmailAndCode() {
      this.validateEmail()
      this.validateCode()
      
      if (this.errors.email || this.errors.code) return
      
      try {
        uni.showLoading({ title: '验证中...' })
        
        console.log('🔍 验证邮箱和验证码')
        
        // 调用后端接口验证
        await authService.verifyEmailCode({
          email: this.formData.email,
          code: this.formData.code,
          type: 'reset_password'
        })
        
        uni.hideLoading()
        
        // 验证成功，保存验证信息，进入下一步
        this.verifiedEmail = this.formData.email
        this.verifiedCode = this.formData.code
        this.currentStep = 2
        
        uni.showToast({
          title: '验证成功',
          icon: 'success'
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('验证失败:', error)
        uni.showToast({
          title: error.message || '验证失败',
          icon: 'none'
        })
      }
    },
    
    // 重置密码
    async resetPassword() {
      this.validateNewPassword()
      this.validateConfirmPassword()
      
      if (this.errors.newPassword || this.errors.confirmPassword) return
      
      try {
        uni.showLoading({ title: '重置中...' })
        
        console.log('🔑 重置密码')
        
        // 调用后端接口重置密码
        await authService.resetPassword({
          email: this.verifiedEmail,
          code: this.verifiedCode,
          newPassword: this.formData.newPassword
        })
        
        uni.hideLoading()
        
        // 重置成功，进入完成页面
        this.currentStep = 3
        
      } catch (error) {
        uni.hideLoading()
        console.error('密码重置失败:', error)
        uni.showToast({
          title: error.message || '重置失败',
          icon: 'none'
        })
      }
    },
    
    // 密码显示切换
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    // 跳转到登录页
    goToLogin() {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.status-bar {
  background: transparent;
}

.top-nav {
  position: fixed;
  top: var(--status-bar-height, 20px);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  z-index: 100;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      font-size: 40rpx;
      color: #fff;
      font-weight: bold;
    }
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #fff;
    }
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.content {
  padding: calc(var(--status-bar-height, 20px) + 88rpx + 40rpx) 40rpx 40rpx;
}

.steps {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 60rpx;
  padding: 0 20rpx;
  
  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
    flex: 0 0 auto;
    
    .step-circle {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      
      .step-number {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
      }
    }
    
    .step-text {
      font-size: 22rpx;
      color: rgba(255, 255, 255, 0.7);
      transition: all 0.3s ease;
    }
    
    &.active {
      .step-circle {
        background: #fff;
        
        .step-number {
          color: #667eea;
        }
      }
      
      .step-text {
        color: #fff;
        font-weight: 600;
      }
    }
    
    &.completed {
      .step-circle {
        background: #4ade80;
      }
    }
  }
  
  .step-line {
    flex: 1;
    height: 2rpx;
    background: rgba(255, 255, 255, 0.3);
    margin: 0 16rpx;
    transition: all 0.3s ease;
    
    &.active {
      background: #fff;
    }
  }
}

.step-content {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-card {
  background: #fff;
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  
  .form-title {
    font-size: 40rpx;
    font-weight: 700;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .form-desc {
    font-size: 26rpx;
    color: #999;
    display: block;
    margin-bottom: 50rpx;
  }
  
  .form-group {
    margin-bottom: 40rpx;
    
    .form-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      display: block;
      margin-bottom: 20rpx;
    }
    
    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      
      .form-input {
        flex: 1;
        height: 90rpx;
        background: #f5f5f5;
        border-radius: 16rpx;
        padding: 0 80rpx 0 30rpx;
        font-size: 28rpx;
        color: #333;
        border: 2rpx solid transparent;
        transition: all 0.3s ease;
        box-sizing: border-box;
        
        &:focus {
          background: #fff;
          border-color: #667eea;
        }
      }
      
      .input-icon {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        font-size: 36rpx;
      }
      
      &.code-wrapper {
        display: flex;
        gap: 10rpx;
        
        .form-input {
          flex: 1;
          padding: 0 30rpx;
        }
        
        .code-btn {
          width: 180rpx;
          height: 90rpx;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
          font-size: 24rpx;
          border-radius: 12rpx;
          border: none;
          flex-shrink: 0;
          
          &::after {
            border: none;
          }
          
          &[disabled] {
            background: #ddd;
            color: #999;
          }
        }
      }
    }
    
    .error-text {
      font-size: 22rpx;
      color: #ff4757;
      display: block;
      margin-top: 12rpx;
      padding-left: 10rpx;
    }
  }
  
  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
    border-radius: 16rpx;
    border: none;
    margin-top: 20rpx;
    
    &::after {
      border: none;
    }
    
    &[disabled] {
      background: #ddd;
      color: #999;
    }
  }
}

.success-card {
  background: #fff;
  border-radius: 32rpx;
  padding: 80rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .success-icon {
    width: 120rpx;
    height: 120rpx;
    background: #4ade80;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60rpx;
    color: #fff;
    margin-bottom: 40rpx;
  }
  
  .success-title {
    font-size: 40rpx;
    font-weight: 700;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .success-desc {
    font-size: 26rpx;
    color: #999;
    text-align: center;
    line-height: 1.6;
    margin-bottom: 60rpx;
  }
  
  .login-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
    border-radius: 16rpx;
    border: none;
    
    &::after {
      border: none;
    }
  }
}
</style>


